package cube.net.frame;

import java.util.List;

import cube.net.socket.SocketConnect;
import cube.net.socket.SocketListener;

/**
 * 帧接收器，监听收到的Socket数据并转换为接收帧
 * 
 * @author abiao
 */
public abstract class FrameRecver extends SocketListener {

    /**
     * 帧发送器
     */
    private FrameSender frameSender;

    /**
     * 帧构建器
     */
    private FrameBuilder frameBuilder;

    /**
     * FrameListener
     */
    public FrameRecver(FrameSender frameSender, FrameBuilder frameBuilder) {
        this.frameSender = frameSender;
        this.frameBuilder = frameBuilder;
    }

    /**
     * 接收连接池数据
     */
    public void recv(SocketConnect conn, byte[] data) {
        handleRecvData(conn, data);
    }

    /**
     * 处理接收到的数据
     */
    private void handleRecvData(SocketConnect conn, byte[] data) {
        watchData(conn.getIP(), conn.getPort(), data);
        List<byte[]> datas = frameBuilder.split(data);
        for (int i = 0; i < datas.size(); i++) {
            byte[] pureData = frameBuilder.unseal(datas.get(i));
            if (pureData != null) {
                pureDataToFrame(conn, pureData);
            }
        }
    }

    /**
     * 将接收到的数据转换为帧对象
     */
    private void pureDataToFrame(SocketConnect conn, byte[] data) {
        NetFrame frame = (NetFrame) frameBuilder.getFrame(data);
        if (frame != null) {
            frame.setFrameIP(conn.getIP());
            frame.setFramePort(conn.getPort());
            handleRecvFrame((RecvFrame) frame);
        }
    }

    /**
     * 按接收帧类型处理接收帧
     */
    private void handleRecvFrame(RecvFrame recvFrame) {
        if (recvFrame instanceof RequestFrame) {
            recvRequestFrame(recvFrame);
        }
        if (recvFrame instanceof ResponseFrame) {
            frameSender.putRecvResponseFrame((NetFrame) recvFrame);
        }
    }

    /**
     * 接收请求帧
     */
    public abstract void recvRequestFrame(RecvFrame recvFrame);

    /**
     * 查看接收到的数据
     */
    public abstract void watchData(String ip, int port, byte[] data);
}
